
layui.use(['form', 'layedit', 'laydate',"table",'upload'], function() {
    var $ = layui.jquery
        , upload = layui.upload;
    var table = layui.table;
    var form = layui.form
        , layer = layui.layer
        , layedit = layui.layedit
        , laydate = layui.laydate;

    //自定义验证规则
    form.verify({

        search: function (value) {
            if(!new RegExp("^[+]{0,1}(\\d+)$").test(value)&&value != null&&value != ""){
                return '热搜词排序为正整数';
            }
            if (value >999999){
                return '热搜词排序数过大';

            }
        }

    });

    //监听工具条
    table.on('tool(demo)', function(obj){
        var data = obj.data;
        if(obj.event === 'detail'){
            $.ajax({
                url:"/topicController/getUrl",
                type:"GET",
                data:{id:data.id},
                success:function(data,status,xhr){
                    if(xhr.status == 200){

                        window.open(data)
                    }
                }
            })
        } else if(obj.event === 'del'){
            layer.confirm('确定删除吗?', function(index){
                $.ajax({
                    url:"/topicController/delById",
                    type:"POST",
                    data:{id:data.id},
                    dataType:"json",
                    success:function(data,status,xhr){
                        if (xhr.code == -1){
                            top.location.href="/pageController/login"

                        }
                        if(xhr.status == 204){
                            layer.alert('删除成功', {icon: 1}, function(index){
                                layer.closeAll("page");
                                layer.close(index);
                                var curr = sessionStorage.getItem("curr");
                                table.reload('testReload',{page:{curr:curr}});
                            });
                        }else{
                            layer.alert('操作失败', {icon: 5});
                        }
                    }
                })
                layer.close(index);

            });
        } else if(obj.event === 'edit'){
            sessionStorage.setItem("bannerPicId",data.bannerPicId);
            var  number = sessionStorage.getItem("bannerNumber")
            if (number >=6 &&( data.bannerPicId == null || data.bannerPicId == "")){
                $("#uploadBanner").hide()
            }else if(number >=6 && data.bannerPicId != null && data.bannerPicId != ""){
                $("#uploadBanner").show()
            }else {
                $("#uploadBanner").show()
            }

            $('#topicId').val(data.id);
            $("input[name='name']").val(data.name )
            if (data.videoNumber == null){
                $("#videoNumber").text("0视频数")
            }else{
                $("#videoNumber").text(data.videoNumber+"视频数")
            }
             if (data.headPortraitId != null && data.headPortraitId != ""){

                 $("input[name='headPortraitId']").val(data.headPortraitId)
                 $("#topicImage").attr("src",data.coverImageUrl)
                 $("#topicImage").show()
             }else{
                 $("input[name='headPortraitId']").val("")
                 $("#topicImage").hide()
             }
            if (data.description != null){

                $('textarea[name="description"]').val(data.description)
            }else {
                $('textarea[name="description"]').val("");
            }
            if (data.bannerPicId != null && data.bannerPicId != "" ){
                // $("#uploadBanner").show()
                $("input[name='bannerPicId']").val(data.bannerPicId)
                $("#bannerImage").attr("src",data.bannerImageUrl)
                $("#bannerImage").show();
            }else {
                // $("#uploadBanner").hide()
                $("input[name='bannerPicId']").val("")
                $("#bannerImage").hide()
            }

            if(data.isHotPush == 1){
                $("input[name='isHotPush']").prop("checked",true);
                $('#banner').show();
            }else{
                $("input[name='isHotPush']").prop("checked",false);
                $('#banner').hide();
            }

            if(data.isRanking == 1){
                $("input[name='isRanking']").prop("checked",true);
            }else{
                $("input[name='isRanking']").prop("checked",false);

            }

            if(data.isHotSearch == 1){
                $("input[name='isHotSearch']").prop("checked",true);
                $('#hotSort').show();
            }else{
                $("input[name='isHotSearch']").prop("checked",false);
                $('#hotSort').hide();

            }
            $("input[name='searchIndex']").val(data.searchIndex)
            form.render();

            var  width=($(window).width()*0.6);
            var height=($(window).height()*0.9);
            layer.open({
                type: 1,
                closeBtn: 0,
                area: [width + 'px', height + 'px'],//大小
                content: $("#topic"),
                skin: "layui-layer-molv",
                title:  "话题:"+data.name
                ,btnAlign: 'c'
                ,btn: ['保存', '取消']
                ,yes: function(index, layero){
                    layero.find('form').find('button[lay-submit]').click();
                    return false
                }
                ,btn2: function(){
                    layer.closeAll();
                }
            })
        }
    });



    //checkbox监控
    form.on('checkbox(hotPush)', function(data){
        if(data.elem.checked){
            var  number = sessionStorage.getItem("bannerNumber")
            if (number >=6){
                layer.msg("有banner图的话题至多为6个")

            }
            $('#banner').show();
        }else{
            $('#banner').hide();
            $("input[name='bannerPicId']").val("")
            $('#bannerImage').attr("src","");
            $('#bannerImage').hide()


        }
    });

    form.on('checkbox(hotSearch)', function(data){
        if(data.elem.checked){
            $('#hotSort').show();
        }else{
            $('#hotSort').hide();
            $("input[name='searchIndex']").val("")
        }
    });

    //提交新增与更新
    form.on('submit(addAndUpdate)', function(data){
        var  number = sessionStorage.getItem("bannerNumber")
      var  description= data.field.description
        if (description.length >100){
            layer.alert('话题描述在100个字符以内', {icon: 5});
            return false;
        }
        //isHotPush处理值
        if(data.field.isHotPush == "on") {
            data.field.isHotPush = "1";
            var  number = sessionStorage.getItem("bannerNumber")
           var oldBannerPicId= sessionStorage.getItem("bannerPicId")
            var bannerPicId = $("input[name='bannerPicId']").val();
            if (number ==6 &&isNull(bannerPicId)&& isNull(oldBannerPicId)){
                layer.alert('有banner图的话题至多为6个', {icon: 5});
                return false;
            }else if ( number <6 &&isNull(bannerPicId)&& (!isNull(oldBannerPicId))){

                layer.alert('请选择热推banner图', {icon: 5});
                return false;
            }else if ( number <6 &&isNull(bannerPicId)&& isNull(oldBannerPicId)){

                layer.alert('请选择热推banner图', {icon: 5});
                return false;
            }else  if (number ==6 &&isNull(bannerPicId)&& (!isNull(oldBannerPicId))){
                layer.alert('请选择热推banner图', {icon: 5});
                return false;
            }
        }
         else {
            data.field.isHotPush = "0";
        }
        //isRanking处理值
        if(data.field.isRanking == "on") {
            data.field.isRanking = "1";
        } else {
            data.field.isRanking = "0";
        }

        //isHotSearch处理值
        if(data.field.isHotSearch == "on") {
            data.field.isHotSearch = "1";
            if  (data.field.searchIndex == null || data.field.searchIndex == "" ){
                layer.alert('请填写热搜排序', {icon: 5});
                return false;
            }

        }

         else {
            data.field.isHotSearch = "0";
        }

        $.ajax({
            url:"/topicController/update",
            type:"PUT",
            data:data.field,
            dataType:"json",
            success:function(data,status,xhr){
                if(xhr.code == -1){
                    top.location.href="/pageController/login"
                }
                if(xhr.status == 204){
                    layer.alert('更新成功', {icon: 1}, function(index){
                        layer.closeAll("page");
                        layer.close(index);
                        var curr = sessionStorage.getItem("curr");
                        table.reload('testReload',{page:{curr:curr}});
                    });
                }

                else if(xhr.status == 500){
                    layer.alert('操作失败', {icon: 5});
                }

            }
        })
        return false;
    });

    $(function () {
        if($('#hotPush').is(':checked')){
            $('#banner').show();
        }else if (!$('#hotPush').is(':checked')){
            $('#banner').hide();
        }

        if($('#hotSearch').is(':checked')){
            $('#hotSort').show();
        }else if (!$('#hotSearch').is(':checked')){
            $('#hotSort').hide();
        }
    })

    //图片上传
    //topic
    var uploadInst = upload.render({
        elem: '#uploadTopic'
        ,url: '/common/upload'
        ,before: function(obj){
            layer.load();
        }

        ,done: function(data,status,xhr){
            layer.closeAll('loading');
            //如果上传失败
            if(xhr.code > 0){
                return layer.msg('上传失败');
            }
            //上传成功
            $('#topicImage').attr("src",data.url);
            $('input[name="headPortraitId"]').val(data.picId);

            $("#topicImage").show()
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#topicText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });
    //banner
    var uploadInst = upload.render({
        elem: '#uploadBanner'
        ,url: '/common/upload'
        ,before: function(obj){
            layer.load();
            var  number = sessionStorage.getItem("bannerNumber")
            if (number > 6){
                return layer.msg('有banner图的话题至多为6个,此图片不会保存');
            }
        }

        ,done: function(data,status,xhr){
            layer.closeAll('loading');
            if(data.code > 0){
                return layer.msg('上传失败');
            }
            //上传成功
            $('#bannerImage').attr("src",data.url);
            $('input[name="bannerPicId"]').val(data.picId);
            $('#bannerImage').show()
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });
});



